var mvcJspModule = angular.module('mvcJspModule',['ngFileUpload','ui.bootstrap','ngSanitize','ionic']);
mvcJspModule.controller('mvcJspCtrl',  function($rootScope,$scope, $http,$compile,$modal,Upload,$ionicPopup){
    // 评论参数
    $scope.comments = {
        inner: '',
        commentCheck: false,
        isEditor: false,
        PersonLists: [],
        PartLists: [],
        AltUserLists: [],
        HistAltLists: [], // 已经@过的
        imgList: [],
        filesList: [],
        atUser: []
    };
    $scope.init = function() {
        // 获取评论数据
        $scope.commentsDetail = {
            list: []
        };
        $http({
            method:'GET',
            url:'/Portal/Workflow/WorkflowComments',
            params : {
                "instanceId" : $.MvcSheetUI.SheetInfo == null ? "" : $.MvcSheetUI.SheetInfo.InstanceId

            }
        }).success(function(result){
            if (result.code == 200) {
                $scope.commentsDetail.list = result.data;
            } else {
                //
            }
        });
    };
    $scope.init();


    // 预览附件
    $scope.PreviewFile = function(item, index) {

            let list = '';
            var url = window.location.href;

            var _PORTALROOT_GLOBAL = window.localStorage.getItem("H3.PortalRoot") ? window.localStorage.getItem("H3.PortalRoot") : "/Portal";
            url = url.split(_PORTALROOT_GLOBAL)[0];
            list = url + _PORTALROOT_GLOBAL + '/' + item.url;
            const a = document.createElement('a'); // 创建a标签
            a.setAttribute('download', item.fileName);// download属性
            a.setAttribute('href', list);// href链接
            a.click()

    };

    // 图片预览
    $scope.imgPreview = function(item, index) {
        // console.log(item,index);
        // let previewUrl = [];
        let list = '';
        // let arr = [];
        var url = window.location.href;

        var _PORTALROOT_GLOBAL = window.localStorage.getItem("H3.PortalRoot") ? window.localStorage.getItem("H3.PortalRoot") : "/Portal";
        url = url.split(_PORTALROOT_GLOBAL)[0];
        list = url + _PORTALROOT_GLOBAL + '/' + item.url;
        // console.log(list, 'list');
        // console.log(url, 'url');

            const a = document.createElement('a'); // 创建a标签
            a.setAttribute('download', item.fileName);// download属性
            a.setAttribute('href', list);// href链接
            a.click();

    };


    // 添加评论
    $scope.addDataDetail = function(personId) {
        var str = $scope.comments.inner.replace(/<span\s*[^>]*>(.*?)<\/span>/ig,"");
        $http({
            method: 'POST',
            url: '/Portal/Workflow/addWorkflowComment',
            data:{
                workItemId:  $.MvcSheetUI.SheetInfo.WorkItemId,
                userId: $.MvcSheetUI.SheetInfo.UserID,
                userName : $.MvcSheetUI.SheetInfo.UserName,
                instanceId: $.MvcSheetUI.SheetInfo.InstanceId,
                sheetCode: '',
                notifyUserIds: '',
                content: $scope.comments.inner,
                contentStr: str, // 不带标签的文本
                needCC: false,
                attachments: [...$scope.comments.imgList,...$scope.comments.filesList]
    }
    })
    .success(function (result, header, config, status) {
            $.LoadingMask.Hide();
            if (result.code === 200) {
                location.reload([true])
            } else {

            }
        })
            .error(function (status) {
                $.MvcSheetUI.IonicFramework.fcommonJS.loadingShow('服务器响应错误');
                setTimeout(() => {
                    $.MvcSheetUI.IonicFramework.fcommonJS.loadingHide()
            },1000);
            });
    };

    // 图片
    $scope.uploadImg = function (file) {
        if (!file) {
            return false
        }
        if ((file.size / (1024*1024)) > 10) {
            $.MvcSheetUI.IonicFramework.fcommonJS.loadingShow('图片大小不能大于10M');
            setTimeout(() => {
                $.MvcSheetUI.IonicFramework.fcommonJS.loadingHide()
        },2000);
            return false
        }
        $.LoadingMask.Show('图片上传中...', true);
        Upload.upload({
            url: '/Portal/Workflow/uploadWorkflowCommentAttachment',
            fields: {'MultipartFile': file.name, 'uploadByImage': true},
            file: file
        })
            .progress(function (evt) {
                // var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
                // console.log('progress: ' + progressPercentage + '% ' + evt.config.file.name);
            })
            .success(function (result, status, headers, config) {
                $.LoadingMask.Hide();
                if (result.code === 200) {
                    $scope.comments.imgList.push(result.data);
                    $ionicPopup.alert({
                        title: '提示',
                        template: '<i class="icon ion-checkmark-circled"></i>上传成功'
                    });
                } else {
                    $ionicPopup.alert({
                        title: '提示',
                        template: '<p><i class="icon ion-close-circled"></i>上传失败</p>'
                    });
                }
            })
            .error(function (data, status, headers, config) {
                $.LoadingMask.Hide();
                $ionicLoading.hide();
                var alertPopup = $ionicPopup.alert({
                    title: '提示',
                    template: '<p><i class="icon ion-close-circled"></i>上传失败</p>'
                });
                alertPopup.then(function(res) {
                    // console.log('Thank you for not eating my delicious ice cream cone');
                    $ionicLoading.hide();
                });
            })
    };

    // 附件
    $scope.uploadFiles = function (files) {
        // console.log(files, 'file');
        if (!files[0]) {
            return false
        }
        if((files[0].size/ (1024*1024)) > 30) {
            $.MvcSheetUI.IonicFramework.fcommonJS.loadingShow('附件大小不能大于20M');
            setTimeout(() => {
                $.MvcSheetUI.IonicFramework.fcommonJS.loadingHide()
        },2000);
            return files
        }
        $.LoadingMask.Show('图片上传中...', true);
        Upload.upload({
            url: '/Portal/Workflow/uploadWorkflowCommentAttachment',
            fields: {'MultipartFile ': files[0].name, 'uploadByImage': false},
            file: files[0]
        })
            .progress(function (evt) {
                // var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
                // console.log('progress: ' + progressPercentage + '% ' + evt.config.file.name);
            })
            .success(function (result, status, headers, config) {
                $.LoadingMask.Hide();
                if (result.code === 200) {
                    $scope.comments.filesList.push(result.data);
                    $ionicPopup.alert({
                        title: '提示',
                        template: '<i class="icon ion-checkmark-circled"></i>上传成功'
                    });
                } else {
                    $ionicPopup.alert({
                        title: '提示',
                        template: '<p><i class="icon ion-close-circled"></i>上传失败</p>'
                    });
                }
            })
            .error(function (data, status, headers, config) {
                $.LoadingMask.Hide();
                $ionicLoading.hide();
                let alertPopup = $ionicPopup.alert({
                    title: '提示',
                    template: '<p><i class="icon ion-close-circled"></i>上传失败</p>'
                });
                alertPopup.then(function(res) {
                    // console.log('Thank you for not eating my delicious ice cream cone');
                    $ionicLoading.hide();
                });
            })
    };

    //删除图片
    $scope.deleteImg = function(item, index) {
        $scope.comments.imgList.splice(index,1)
    };

    // 删除文件
    $scope.deleteFile = function(item, index) {
        $scope.comments.filesList.splice(index,1)
    };



})
